import React, { Component } from 'react'

import {
  EditWrapper,
  Preview
} from '../style.js'

import { Upload, Button, message } from 'antd';
import axios from 'axios'

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default class Avatar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      imageUrl: '',
      loading: false,
      fileList: null
    }
  }
  componentWillMount() {
    setTimeout(() => {
      let cH = document.getElementById('p_content').clientHeight
      let bH = document.body.clientHeight - 180
      let t = document.getElementById('footer')
      if(cH >= bH || bH<=800) {
        t.style.position= 'relative'
      }
    }, 300);
  }
  handleChange = info => {
    // console.log('handleChange')
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name}上传成功！`);
      this.setState({
        loading: false
      })
    }
  }
  handleUpload = () => {
    const formData = new FormData();
    formData.append('file', this.state.fileList)
    axios({
      url: '/user/upload/avatar',
      method: 'post',
      processData: false,
      data: formData
    }).then(res=> {
      if(res.data.code === 20000) {
        message.success('保存成功！')
        // console.log('this.props', this.props)
        this.props.saveAvatar(res.data.data)
      } else {
        message.success(res.msg)
      }
    });
  }
  render() {
    const props = {
      name: 'file',
      action: '/user/upload/avatar',
      headers: {
        authorization: 'authorization-text',
      },
      showUploadList: false,
      beforeUpload: (file, list) => {
        this.setState(state => ({
          fileList: file
        }));
        getBase64(file, imageUrl =>
          this.setState({
            imageUrl,
            loading: false,
          }),
        );
        return false;
      }
    };
    return (
      <div>
        <div className="clearfix">
          <EditWrapper>
            <Upload {...props} onChange={this.handleChange} accept=".jpg, .jpeg, .png">
              <Button loading={this.state.uploading}>
                上传头像
              </Button>
            </Upload>
            <p style={{fontSize: '14px', marginTop: '10px'}}>仅支持JPG、PNG图片格式文件，且文件图片小于8M</p>
            {
              this.state.imageUrl ? <img alt="头像" style={{width: "300px", height: "300px", marginTop: "10px", marginBottom: "10px"}} src={this.state.imageUrl} /> : <img alt="头像" style={{width: "300px", height: "300px", marginTop: "10px", marginBottom: "10px"}} src={require('../img/default_head_photo.png')} /> 
            }
          </EditWrapper>
          <Preview>
            <p>预览</p>
            <p style={{lineHeight: '60px', color: 'rgb(139,202,52)'}}>您上传的头像会自动生成两种尺寸，注意清晰度</p>
            <div>
              <div className="pre-128">
                {
                  this.state.imageUrl ? <img alt="" src={this.state.imageUrl} /> : <img alt="" src={require('../img/default_head_photo.png')} /> 
                }
                <p>128*128像素</p>
              </div>
              <div className="pre-68">
                {
                  this.state.imageUrl ? <img alt="" src={this.state.imageUrl} /> : <img alt="" src={require('../img/default_head_photo.png')} /> 
                }
                <p>68*68像素</p>
              </div>
            </div>
          </Preview>
        </div>
        <Button type="primary"  onClick={this.handleUpload}>保存</Button>
      </div>
    )
  }
}